package eerbaar.v2.gamebuilder.client.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.swing.JOptionPane;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import eerbaar.v2.wait.Wait;
import eerbaar.v2.wait.WaitRegistration;

public class RequestRunner implements Runnable {

    private final HttpPost method;
    private final IRequestProcessor callback;

    public RequestRunner(HttpPost method, IRequestProcessor callback) {
        this.method = method;
        this.callback = callback;
    }

    protected String extractContent(HttpResponse response) throws IOException {

        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        String result = null;
        while ((line = reader.readLine()) != null) {
            if (result == null) {
                result = "";
            }
            result += line;
        }

        return result;
    }

    @Override
    public void run() {

        try {
            HttpClient client = new DefaultHttpClient();
            WaitRegistration reg = Wait.getInstance().startWaiting();

            System.out.println(this.method.getURI());
            HttpResponse response = client.execute(this.method);
            reg.stopWaiting();

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                String data = extractContent(response);
                this.callback.processInWorkerThread(data);

            } else {

                String reason = response.getStatusLine().getReasonPhrase();
                JOptionPane.showMessageDialog(null, reason);
                System.err.println(reason);
            }

        } catch (IOException e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, e.getMessage());
            System.exit(-1);
        }
    }

}
